package cn.android666.netutil

import android.os.Bundle
import android.os.Environment
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import cn.android666.net.util.ApiRequestCallback
import cn.android666.net.util.Nice
import cn.android666.net.util.RequestResult
import cn.android666.net.util.TypeToken
import cn.android666.net.util.download.apkdownload.ApkDownloadPresenter
import cn.android666.netutil.databinding.ActivityMainBinding
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {

    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        binding.asyncRequestButton.setOnClickListener { asyncRequest() }
        binding.syncRequestButton.setOnClickListener { syncRequest() }
        binding.asyncGetStringButton.setOnClickListener { asyncGetString() }
        binding.syncGetStringButton.setOnClickListener { syncGetString() }
        binding.downloadButton.setOnClickListener { downloadApk() }
    }

    private fun asyncGetString() {
        binding.asyncGetStringButton.isEnabled = false
        binding.textView.text = "正在请求中。。。"
        Nice.Builder()
            .get("https://echo.apifox.com/get")
            .addParam("color", "red")
            .addParam("size", "99")
            .addParam("desc", getString(R.string.async_get_string))
            .goString(object : ApiRequestCallback<String>() {
                override fun onApiRequestSuccess(requestResult: String, baseResult: RequestResult<*>?) {
                    binding.textView.text = decodeUnicode(requestResult)
                    binding.asyncGetStringButton.isEnabled = true
                }

                override fun onApiRequestFail(failCause: String, baseResult: RequestResult<*>?) {
                    binding.textView.text = failCause
                    binding.asyncGetStringButton.isEnabled = true
                }
            })
    }

    private fun syncGetString() {
        binding.syncGetStringButton.isEnabled = false
        binding.textView.text = "正在请求中。。。"
        thread {
            val result = Nice.Builder()
                .get("https://echo.apifox.com/get")
                .addParam("color", "red")
                .addParam("size", "99")
                .addParam("desc", getString(R.string.sync_get_string))
                .goStringSync()
            runOnUiThread {
                if (result.isSuccess) {
                    binding.textView.text = decodeUnicode(result.result)
                } else {
                    binding.textView.text = result.error
                }
                binding.syncGetStringButton.isEnabled = true
            }
        }
    }

    private fun asyncRequest() {
        binding.asyncRequestButton.isEnabled = false
        binding.textView.text = "正在请求中。。。"

        Nice.Builder()
            .get("https://echo.apifox.com/get")
            .addParam("name", "even")
            .addParam("age", "18")
            .addParam("desc", getString(R.string.async_request))
            .go(object : ApiRequestCallback<JavaBean>() {
                override fun onApiRequestSuccess(requestResult: JavaBean, baseResult: RequestResult<*>?) {
                    binding.textView.text = requestResult.toString()
                    binding.asyncRequestButton.isEnabled = true
                }

                override fun onApiRequestFail(failCause: String, baseResult: RequestResult<*>?) {
                    binding.textView.text = failCause
                    binding.asyncRequestButton.isEnabled = true
                }
            })
    }

    private fun syncRequest() {
        binding.syncRequestButton.isEnabled = false
        binding.textView.text = "正在请求中。。。"
        thread {
            val result = Nice.Builder()
                .get("https://echo.apifox.com/get")
                .addParam("name", "even")
                .addParam("age", "18")
                .addParam("desc", getString(R.string.sync_request))
                .goSync(object: TypeToken<JavaBean>(){ })
            runOnUiThread {
                if (result.isSuccess) {
                    binding.textView.text = result.result.toString()
                } else {
                    binding.textView.text = result.error
                }
                binding.syncRequestButton.isEnabled = true
            }
        }
    }

    /** 把字符串中的Unicode编码转为对应的中文，当使用gson解析时，它会自动转换 */
    fun decodeUnicode(str: String): String {
        val pattern = Regex("\\\\u([0-9a-fA-F]{4})")
        return pattern.replace(str) {
            val code = it.groupValues[1].toInt(16)
            code.toChar().toString()
        }
    }

    private fun downloadApk() {
        val appName = "拼多多"
        val apkDownloadUrl = "https://cd.pddpic.com/volantis-open/mobile-CI-tag/2025-10-21/fa0a58cb9ba8c6088542d8cc72579814.apk"
        val appPackageName = "com.xunmeng.pinduoduo"
        val appVersionCode = "78000"
        val isForceUpdate = false
        val adp = ApkDownloadPresenter(this, isForceUpdate, null)
        adp.startNewDownload(appName, apkDownloadUrl, appPackageName, appVersionCode, getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)!!)
    }

}